package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    // 通用序列化器：按需替换为你的具体类型，如 User.class、Order.class
    private static final Class<Object> VALUE_TYPE = Object.class;

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);


        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 使用StringRedisSerializer来序列化和反序列化redis的value值
        template.setValueSerializer(new StringRedisSerializer());

        // 设置hash key 和 value 序列化模式
//        template.setHashKeySerializer(new StringRedisSerializer());
//        template.setHashValueSerializer(new StringRedisSerializer());
//
//        template.afterPropertiesSet();

        // value 使用 FastJSON
        FastJson2RedisSerializer<Object> valueSerializer = new FastJson2RedisSerializer<>(VALUE_TYPE);
        template.setValueSerializer(valueSerializer);
        template.setHashValueSerializer(valueSerializer);

        template.afterPropertiesSet(); // 初始化默认序列化器等
        return template;
    }
}
